<template>
<div>
    <div class="category-news-list"
        v-infinite-scroll="loadMore" 
        :infinite-scroll-immediate="false" 
        :infinite-scroll-delay="200"
        :infinite-scroll-distance="10">

        <!-- 骨架屏 -->
        <div v-if="initialLoad" v-for="num in 6" :key="num" class="list-item">
            <div class="list-item-content">
                <el-skeleton style="--el-skeleton-circle-size: 100%" animated :throttle="200">
                    <template #template>
                        <el-skeleton-item variant="text" style="width: 100%;margin-bottom: 10px;"/>
                        <el-skeleton-item variant="text" style="width: 30%" />
                    </template>
                </el-skeleton>
            </div>
        </div>

        <!-- 新闻列表 -->
        <div v-else v-for="news in newsList" :key="news.title" class="list-item" @click="navigateToNewsDetails(news)">
            <div class="list-item-content">
                <div class="list-item-title">{{ news.title }}</div>
                <div class="list-item-subtitle">{{ news.categoryName }} · {{ formatTimeAgo(news.publishTime) }}</div>
            </div>
            <img v-if="news.frontCover" :src="news.frontCover" width="80" height="60" style="border-radius: 6px; object-fit: cover;">
        </div>
        
        <div v-if="isReachBottom" style="text-align: center;margin-bottom: 20px;color: #8e8e93;font-size: 14px;">
            <p>已经到底了~</p>
        </div>
    </div>
</div>
</template>

<script lang="ts" setup>
import { ref,onMounted, watch } from 'vue'
import { useRouter,useRoute } from 'vue-router';
import api from '@/api';
import { NewsStore } from '@/stores/newsInfoStore';
import { TipStore } from '@/stores/tipStore';

const route = useRoute();
const router = useRouter();
const newsStoreObject = NewsStore();
const TipStoreObject = TipStore();

// #region 数据定义
// 父组件传过来的值
const props = defineProps({
    categoryId: String,
})
const News_queryDTO = ref({
    categoryId: props.categoryId,
    status: 1,

    current: 1,
    size: 10,
})
const newsList = ref([])
const initialLoad = ref(true); // 该分类新闻是否第一次加载
const isReachBottom = ref(false); // 是否达到底部
//#endregion


// 日期格式化
function formatTimeAgo(timeStr) {
    // 将传入的时间字符串转换为 Date 对象
    const time = new Date(timeStr);
    // 获取当前时间
    const now = new Date();
    // 计算时间差（单位：毫秒）
    const diff = now.getTime() - time.getTime();

    // 将时间差转换为分钟、小时、天
    const minutes = Math.floor(diff / 1000 / 60);
    const hours = Math.floor(minutes / 60);
    const days = Math.floor(hours / 24);

    // 根据时间差返回对应的时间格式
    if (days > 7) {
        return "7天前";
    } else if (days > 0) {
        return `${days}天前`;
    } else if (hours > 0) {
        return `${hours}小时前`;
    } else if (minutes > 0) {
        return `${minutes}分钟前`;
    } else {
        return "刚刚";
    }
}

// 获取新闻分类名称
const getNewsCategoriesName = (Id) => {
    if (Id != null) {
        return newsStoreObject.newsCategoryInfo.find(ncInfo => ncInfo.id == Id)?.name;
    } else { return null }
};
// 跳转到新闻详情页
const navigateToNewsDetails = (news) => {
    router.push({
        path: '/NewsDetails',
        query: { 
            NewsId: news.id,
            newsCategoryName: getNewsCategoriesName(news.categoryId)
        }
    });
};


// 加载更多
const loadMore = async()=>{
    if(isReachBottom.value == false){
        News_queryDTO.value.current++;
        let Res = await getNewsInCondition()
        newsList.value = newsList.value.concat(Res)

        if(Res.length < 10){
            isReachBottom.value = true; // 新数据不足10条，说明已经到达底部，不再加载更多
        }
    }
}

// 分页获取新闻列表
const getNewsInCondition = async()=>{
    try{
        let res = await api.getNewsInCondition(News_queryDTO.value)
        if(res.data.code == 1){
            return res.data.data.list
        }else{ return [] }
    }catch{
        TipStoreObject.errorTip("未知错误")
        return []
    }
}



watch(()=>props.categoryId, async(newVal,oldVal) =>{
    // 变化到了新的分类，应该清空原本的参数
    News_queryDTO.value = {
        categoryId: newVal,
        status: 1,

        current: 1,
        size: 10,
    }
    isReachBottom.value = false;
    initialLoad.value = true;
    newsList.value = []


    let res = await getNewsInCondition()
    newsList.value = res
    initialLoad.value = false;
    if(res.length < 10){
        isReachBottom.value = true; // 新数据不足10条，说明已经到达底部，不再加载更多
    }
})


onMounted(async() => {
    let res = await getNewsInCondition()
    initialLoad.value = false;
    newsList.value = res
    if(res.length < 10){
        isReachBottom.value = true; // 新数据不足10条，说明已经到达底部，不再加载更多
    }
})

</script>

<style lang="scss" scoped>
.category-news-list {
    flex: 1;
    overflow: auto
}
.list-item {
    display: flex;
    margin-bottom: 16px;
    padding: 10px 30px;
    border-bottom: 1px solid #eaeaea;
    cursor: pointer;
}
.list-item-content {
    flex: 1;
    margin-right: 16px;
}
.list-item-title {
    font-weight: 600;
    font-size: 16px;
    margin-bottom: 15px;
}

.list-item-subtitle {
    color: #8e8e93;
    font-size: 14px;
}
</style>